package demo;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class TreeEditFrame extends JFrame {

	/**
	 *
	 */
	private static final long serialVersionUID = -8017762200230001186L;

	private DefaultTreeModel model;

	private JTree tree;

	static Socket socket;

	String name = "";

	// PrintStream ps;
	DefaultMutableTreeNode root = null;

	DefaultMutableTreeNode country = new DefaultMutableTreeNode("当前在线");; // @jve:decl-index=0:

	private JButton jButton = null;

	private JButton jButton1 = null;

	public TreeEditFrame() {
		setTitle("TreeEditFrame");
		setSize(275, 600);

		// add scroll pane with tree
		JScrollPane scrollPane = new JScrollPane(tree);
		add(scrollPane, BorderLayout.CENTER);
		makeButtons();

		// consturct tree
		TreeNode root = makeSampleTree();
		model = new DefaultTreeModel(root);
		tree = new JTree(model);
		tree.setEditable(true);
		tree.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent e) {
				if (e.getClickCount() == 2) {
					TreePath path = tree.getSelectionPath();
					if (path == null)
						return;
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
							.getLastPathComponent();
					name = node.getUserObject().toString();
				}
			}
		});
	}

	private TreeNode makeSampleTree() {
		// TODO 自动生成方法存根
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("FeiQ 聊天");

		root.add(country);
		country.add(new DefaultMutableTreeNode("San Diego"));
		country.add(new DefaultMutableTreeNode("Michigan"));
		return root;
	}

	private void makeButtons() {
		// TODO 自动生成方法存根

		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		JButton addSiblingButton = new JButton("Add Sibling");
		addSiblingButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();
				if (selectedNode == null)
					return;

				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode
						.getParent();
				if (parent == null)
					return;

				DefaultMutableTreeNode newNode = new DefaultMutableTreeNode();

				int selectedIndex = parent.getIndex(selectedNode);
				model.insertNodeInto(newNode, parent, selectedIndex + 1);

				// now display nes node

				TreeNode[] nodes = model.getPathToRoot(newNode);
				TreePath path = new TreePath(nodes);
				tree.scrollPathToVisible(path);

			}
		});
		panel.add(addSiblingButton, BorderLayout.WEST);
		JButton addChildButton = new JButton("Add Child");
		addChildButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();
				if (selectedNode == null)
					return;

				DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(
						"New");
				model.insertNodeInto(newNode, selectedNode,
						selectedNode.getChildCount());

				// now display new node
				TreeNode[] nodes = model.getPathToRoot(newNode);
				TreePath path = new TreePath(nodes);
				tree.scrollPathToVisible(path);

			}
		});
		panel.add(addChildButton, BorderLayout.CENTER);

		JButton deleteButton = new JButton("Delete");
		deleteButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
						.getLastSelectedPathComponent();

				if (selectedNode != null && selectedNode.getParent() != null)
					model.removeNodeFromParent(selectedNode);

			}
		});
		panel.add(deleteButton, BorderLayout.EAST);
		panel.add(getJButton(), BorderLayout.NORTH);
		panel.add(getJButton1(), BorderLayout.SOUTH);
		add(panel, BorderLayout.SOUTH);
	}

	/**
	 * This method initializes jButton
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			jButton.setText("刷新");
			jButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("actionPerformed()"); // TODO
					// Auto-generated
					// Event stub
					// actionPerformed()
					ClientListener t;
					try {
						country.removeAllChildren();
						socket = new Socket("211.87.232.105", 7000);
						t = new ClientListener(socket);
						StringBuffer msg = new StringBuffer("CONNECT:");
						String name = "111";
						String ip = InetAddress.getLocalHost().toString();
						msg.append(name + ":" + ip);
						System.out.println(msg);
						/* ps = new PrintStream(socket.getOutputStream()); */
						t.ps.println(msg);
						t.ps.flush();

						System.out.println("222222222222222222222222");
						String tmp = t.getmessage();
						// ///////////////////////////////
						StringTokenizer st = new StringTokenizer(tmp, ":");
						String keyword = st.nextToken();

						// 服务器端传来各种信息的处理
						if (keyword.equals("PEOPLE")) {

							while (st.hasMoreTokens()) {

								String user = st.nextToken();
								System.out.println(user);
								DefaultMutableTreeNode tp = new DefaultMutableTreeNode(
										user);
								country.add(tp);
								tree.updateUI();
							}
						}
						// //////////////////////////////
					} catch (UnknownHostException e1) {
						// TODO 自动生成 catch 块
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO 自动生成 catch 块
						e1.printStackTrace();
					}
					// ClientListener(socket).start();

				}
			});
		}
		return jButton;
	}

	/**
	 * This method initializes jButton1
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setText("群发");
			jButton1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					String message = JOptionPane.showInputDialog(
							TreeEditFrame.this, "请输入群发信息", "信使群发",
							JOptionPane.INFORMATION_MESSAGE);
					if (message != null && !message.equals("")) {
						TreePath[] selectionPaths = tree.getSelectionPaths();
						System.out.println(selectionPaths);
						// Resource.sendGroupMessenger(selectionPaths, message);
					} else if (message != null && message.isEmpty()) {
						JOptionPane.showMessageDialog(TreeEditFrame.this,
								"不能发送空信息！");
					}

				}
			});
		}
		return jButton1;
	}

	public static void main(String[] args) {
		// TODO 自动生成方法存根

		JFrame frame = new TreeEditFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}

	/*
	 * private static Thread ClientListener(Socket socket2) { // TODO 自动生成方法存根
	 * return null; }
	 */
	class ClientListener {
		Socket socket;

		BufferedReader br;

		PrintStream ps;

		String message;

		public ClientListener(Socket s) {
			try {
				socket = s;
				br = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));

				ps = new PrintStream(socket.getOutputStream());
			} catch (IOException ex) {

			}
		}

		public String getmessage() {

			try {
				message = br.readLine();
				System.out.println(message);

			} catch (IOException ex) {

			}

			return message;
		}
	}

	public void closeSocket() {
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException ex) {
				// ta.append("Error: " + ex + "\n");
			}
		}
	}

	// /////////////////////////////////////////////////////////////////////////////////////////////////////////

}
